#include "udpserver.h"
#include <QHostAddress>

UdpServer::UdpServer(QWidget *parent, Qt::WindowFlags f):
    QDialog(parent,f)
{
    setWindowTitle(tr("UDP SERVER"));
    TimerLabel = new QLabel(tr("Timer:"),this);
    TextLineEdit = new QLineEdit(this);
    StartBtn = new QPushButton(tr("START"),this);
    mainLayout = new QVBoxLayout(this);
    mainLayout->addWidget(TimerLabel);
    mainLayout->addWidget(TextLineEdit);
    mainLayout->addWidget(StartBtn);
    //------------functional--------------
    connect(StartBtn,SIGNAL(clicked()),this,SLOT(StartBtnClicked()));
    port = 5555;
    isStarted = false;
    udpsocket = new QUdpSocket(this);
    timer = new QTimer(this);
    //-----------timerout----------------
    connect(timer,SIGNAL(timeout()),this,SLOT(timeout()));

}

UdpServer::~UdpServer()
{

}

void UdpServer::StartBtnClicked()
{
    if(!isStarted)
    {
        StartBtn->setText(tr("STOP"));
        timer->start(1000);
        isStarted = true;
    }
    else
    {
        StartBtn->setText(tr("START"));
        isStarted = false;
        timer->stop();
    }
}

void UdpServer::timeout()
{
    QString msg = TextLineEdit->text();
    int length = 0;
    if(msg=="")
    {
        return;
    }
    if((length=udpsocket->writeDatagram(msg.toLatin1(),msg.length(),QHostAddress::Broadcast,port))!=msg.length())
    {
        return;
    }
}
